import type { ProxyOptions } from "vite";

type ProxyItem = [string, string];

type ProxyList = ProxyItem[];

type ProxyTargetList = Record<string, ProxyOptions>;

/**
 * 创建代理，用于解析 .env.development 代理配置
 * @param list
 */
export function createProxy(list: ProxyList = []) {
  const ret: ProxyTargetList = {};
  for (let [prefix, target] of list) {
    prefix += "/";
    const httpsRE = /^https:\/\//;
    const isHttps = httpsRE.test(target);

    // console.log({ prefix, target });

    // https://github.com/http-party/node-http-proxy#options
    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: path => {
        let ret = path.replace(new RegExp(`^${prefix}`), "/");
        // console.log("ret is ", ret, path);
        return ret;
      },
      configure: (proxy, options) => {
        proxy.on("proxyRes", function (proxyRes, req, res) {
          // proxyRes.headers["Content-Type"] = "application/json; charset=utf-8";
        });
      },
      // https is require secure=false
      ...(isHttps ? { secure: false } : {})
    };
  }
  return ret;
}
